package com.syp.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.syp.lease.common.constant.RedisConstant;
import com.syp.lease.common.exception.LeaseException;
import com.syp.lease.common.result.ResultCodeEnum;
import com.syp.lease.common.utils.JwtUtil;
import com.syp.lease.model.entity.SystemUser;
import com.syp.lease.model.enums.BaseStatus;
import com.syp.lease.web.admin.service.LoginService;
import com.syp.lease.web.admin.service.SystemUserService;
import com.syp.lease.web.admin.vo.login.CaptchaVo;
import com.syp.lease.web.admin.vo.login.LoginVo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo getCaptcha() {

        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);

        String code = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        String image = specCaptcha.toBase64();
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        return new CaptchaVo(image, key);
    }

    /**
     * 登录功能实现方法
     *
     * @param loginVo 登录视图对象，包含用户输入的用户名、密码和验证码信息
     * @return 登录成功后生成的JWT令牌
     * @throws LeaseException 当验证码错误、过期，密码错误或用户不存在时抛出异常
     */
    @Override
    public String login(LoginVo loginVo) {
        // 检查验证码是否为空，为空则抛出异常
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        // 从Redis中获取验证码，检查是否为空，为空则抛出异常
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (!StringUtils.hasText(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        // 比较用户输入的验证码和Redis中的验证码是否一致，不一致则抛出异常
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        // 检查密码是否为空，为空则抛出异常
        if (!StringUtils.hasText(loginVo.getPassword())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_PASSWORD_NOT_FOUND);
        }
        // 查询数据库中是否存在该用户名的用户，不存在则抛出异常
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        long count = systemUserService.count(queryWrapper);
        if (count == 0) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        // 获取用户信息，检查用户状态是否为禁用，为禁用则抛出异常
        SystemUser systemUser = systemUserService.getOne(queryWrapper);
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        // 对用户输入的密码进行MD5加密，并与数据库中的密码进行比较，不一致则抛出异常
        String md5Hex = DigestUtils.md5Hex(loginVo.getPassword());
        if (!md5Hex.equals(systemUser.getPassword())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 登录成功，创建包含用户信息的Map，用于生成JWT令牌
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", systemUser.getId());
        map.put("userName", systemUser.getUsername());
        // 根据用户信息和密钥生成JWT令牌并返回
        return JwtUtil.createToken(JwtUtil.ADMIN_SECRET_KEY, 60 * 60 * 1000L, map);
    }
}
